"""
verify create agent with knowledge API
test if workspace_id parameter is properly supported
"""
import sys
from pathlib import Path

# Add project root to Python path
project_root = Path(__file__).parent.parent
sys.path.insert(0, str(project_root))

import logging
from src.llm.hiagent_app.services.agent_knowledge_service import AgentKnowledgeService
from src.llm.hiagent_app.config.hiagent_config import HiAgentConfig

# configure logging
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)
logger = logging.getLogger(__name__)


def test_create_with_default_workspace():
    """test create with default workspace_id"""
    logger.info("=" * 60)
    logger.info("Test 1: create agent with default workspace_id")
    logger.info("=" * 60)

    service = AgentKnowledgeService()
    default_ws_id = HiAgentConfig.DEFAULT_WORKSPACE_ID
    logger.info(f"Using default workspace_id: {default_ws_id}")

    try:
        agent_id, knowledge_id = service.create_agent_with_knowledge(
            agent_name="test_agent_default_ws",
            knowledge_name="test_knowledge_default_ws",
            agent_description="test with default workspace"
        )
        logger.info(f"SUCCESS - Agent ID: {agent_id}, Knowledge ID: {knowledge_id}")

        # cleanup
        logger.info("Cleaning up test resources...")
        service._cleanup_resources(agent_id, knowledge_id, default_ws_id)
        return True
    except Exception as e:
        logger.error(f"FAILED - Error: {str(e)}")
        return False


def test_create_with_custom_workspace():
    """test create with custom workspace_id"""
    logger.info("\n" + "=" * 60)
    logger.info("Test 2: create agent with custom workspace_id")
    logger.info("=" * 60)

    service = AgentKnowledgeService()
    custom_ws_id = HiAgentConfig.DEFAULT_WORKSPACE_ID  # use same as default for testing
    logger.info(f"Using custom workspace_id: {custom_ws_id}")

    try:
        agent_id, knowledge_id = service.create_agent_with_knowledge(
            agent_name="test_agent_custom_ws",
            knowledge_name="test_knowledge_custom_ws",
            agent_description="test with custom workspace",
            workspace_id=custom_ws_id
        )
        logger.info(f"SUCCESS - Agent ID: {agent_id}, Knowledge ID: {knowledge_id}")

        # cleanup
        logger.info("Cleaning up test resources...")
        service._cleanup_resources(agent_id, knowledge_id, custom_ws_id)
        return True
    except Exception as e:
        logger.error(f"FAILED - Error: {str(e)}")
        return False


def test_api_request_model():
    """test API request model structure"""
    logger.info("\n" + "=" * 60)
    logger.info("Test 3: API request model structure")
    logger.info("=" * 60)

    try:
        from src.routers.hiagent_center import CreateAgentWithKnowledgeRequest

        # test with workspace_id
        request = CreateAgentWithKnowledgeRequest(
            agent_name="test_agent",
            knowledge_name="test_knowledge",
            agent_description="test description",
            workspace_id="test_workspace_id"
        )

        logger.info(f"Request model created successfully:")
        logger.info(f"  agent_name: {request.agent_name}")
        logger.info(f"  knowledge_name: {request.knowledge_name}")
        logger.info(f"  agent_description: {request.agent_description}")
        logger.info(f"  workspace_id: {request.workspace_id}")

        return True
    except Exception as e:
        logger.error(f"FAILED - Error: {str(e)}")
        return False


def main():
    """main test function"""
    logger.info("Starting create-with-knowledge API verification")
    logger.info("=" * 60)

    results = {
        "test_api_request_model": test_api_request_model(),
        "test_default_workspace": test_create_with_default_workspace(),
        "test_custom_workspace": test_create_with_custom_workspace()
    }

    logger.info("\n" + "=" * 60)
    logger.info("Test Results Summary")
    logger.info("=" * 60)
    for test_name, result in results.items():
        status = "PASS" if result else "FAIL"
        logger.info(f"{test_name}: {status}")

    all_passed = all(results.values())

    logger.info("\n" + "=" * 60)
    if all_passed:
        logger.info("ALL TESTS PASSED")
        logger.info("=" * 60)
        logger.info("workspace_id parameter is now properly supported:")
        logger.info("1. AgentKnowledgeService accepts optional workspace_id in __init__")
        logger.info("2. create_agent_with_knowledge accepts optional workspace_id parameter")
        logger.info("3. API endpoint accepts workspace_id in request body")
        logger.info("4. All internal methods properly pass workspace_id")
    else:
        logger.info("SOME TESTS FAILED")
        logger.info("=" * 60)
        logger.info("Please review the error messages above")


if __name__ == "__main__":
    main()
